<template>
    <div class="food-manage-container">
      <!-- 搜索和操作区域 -->
      <div class="operation-area">
        <el-card shadow="hover">
          <div class="search-wrapper">
            <el-input
                v-model="searchQuery"
                placeholder="输入食品名称或分类搜索"
                clearable
                class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
  
            <el-select v-model="categoryFilter" placeholder="食品分类" clearable>
              <el-option label="全部" value="" />
              <el-option label="海鲜" value="海鲜" />
              <el-option label="主食" value="主食" />
              <el-option label="小吃" value="小吃" />
              <el-option label="肉类" value="肉类" />
              <el-option label="火锅" value="火锅" />
            </el-select>
  
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
  
            <el-button type="success" @click="handleAddFood" v-if="isAdmin">
              <el-icon><Plus /></el-icon>新增食品
            </el-button>
          </div>
        </el-card>
      </div>
  
      <!-- 食品表格 -->
      <el-card shadow="hover" class="table-card">
        <el-table
            :data="filteredFoodList"
            border
            stripe
            style="width: 100%"
            v-loading="loading"
        >
          <el-table-column type="index" width="50" label="序号" />
  
          <el-table-column prop="food.name" label="食品名称" width="150" />
  
          <el-table-column prop="cityName" label="所属城市" width="120" />
  
          <el-table-column prop="food.category" label="分类" width="100">
            <template #default="scope">
              <el-tag :type="getFoodCategoryType(scope.row.food.category)">
                {{ scope.row.food.category }}
              </el-tag>
            </template>
          </el-table-column>
  
          <el-table-column prop="food.description" label="描述">
            <template #default="scope">
              <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="scope.row.food.description"
                  placement="top-start"
              >
                <div class="description-cell">{{ scope.row.food.description }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
  
          <el-table-column label="图片" width="80">
            <template #default="scope">
              <el-image
                  v-if="scope.row.food.image"
                  :src="scope.row.food.image"
                  :preview-src-list="[scope.row.food.image]"
                  fit="cover"
                  class="food-image"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div v-else class="no-image">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-table-column>
  
          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                  size="small"
                  @click="handleViewFood(scope.row)"
                  type="primary"
                  link
              >
                查看
              </el-button>
  
              <el-button
                  size="small"
                  @click="handleEditFood(scope.row)"
                  type="primary"
                  link
                  v-if="isAdmin"
              >
                编辑
              </el-button>
  
              <el-button
                  size="small"
                  @click="handleDeleteFood(scope.row)"
                  type="danger"
                  link
                  v-if="isAdmin"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalFoods"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 食品详情对话框 -->
      <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增食品' : dialogType === 'edit' ? '编辑食品' : '食品详情'"
          width="600px"
      >
        <el-form
            ref="foodFormRef"
            :model="foodForm"
            :rules="foodFormRules"
            label-width="100px"
            :disabled="dialogType === 'view'"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="食品名称" prop="name">
                <el-input v-model="foodForm.name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属城市" prop="cityId">
                <el-select v-model="foodForm.cityId" placeholder="请选择城市">
                  <el-option label="石家庄" :value="1" />
                  <!-- 这里可以添加更多城市选项 -->
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="分类" prop="category">
                <el-select v-model="foodForm.category" placeholder="请选择分类">
                  <el-option label="海鲜" value="海鲜" />
                  <el-option label="主食" value="主食" />
                  <el-option label="小吃" value="小吃" />
                  <el-option label="肉类" value="肉类" />
                  <el-option label="火锅" value="火锅" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-form-item label="描述" prop="description">
            <el-input v-model="foodForm.description" type="textarea" rows="3" />
          </el-form-item>
  
          <el-form-item label="图片" prop="image">
            <el-upload
                class="food-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
            >
              <img v-if="foodForm.image" :src="foodForm.image" class="food-cover" />
              <el-icon v-else class="food-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
  
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
                type="primary"
                @click="submitFoodForm"
                v-if="dialogType !== 'view'"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 删除确认对话框 -->
      <el-dialog
          v-model="deleteDialogVisible"
          title="确认删除"
          width="400px"
      >
        <div class="delete-confirm">
          <el-icon class="warning-icon"><WarningFilled /></el-icon>
          <span>确定要删除食品 <strong>{{ selectedFood.food ? selectedFood.food.name : '' }}</strong> 吗？此操作不可恢复！</span>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="confirmDelete">确定删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { ref, reactive, computed, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Plus, WarningFilled, Picture } from '@element-plus/icons-vue'
  import { selectAllFood, addNewFood, updateFood, deleteFood } from "@/api/food";
  
  export default {
    name: 'FoodManagement',
    components: {
      Search,
      Plus,
      WarningFilled,
      Picture
    },
    setup() {
      // 状态和数据
      const loading = ref(false);
      const foodList = ref([]);
      const searchQuery = ref('');
      const categoryFilter = ref('');
      const dialogVisible = ref(false);
      const dialogType = ref('view'); // 'view', 'add', 'edit'
      const deleteDialogVisible = ref(false);
      const selectedFood = ref({});
      const currentPage = ref(1);
      const pageSize = ref(10);
      const totalFoods = ref(0);
  
      // 管理员权限判断（实际项目中应该从登录用户信息或权限中获取）
      const isAdmin = ref(true); // 假设当前用户是管理员
  
      // 食品表单
      const foodFormRef = ref(null);
      const foodForm = reactive({
        id: null,
        cityId: 1,
        name: '',
        category: '',
        image: null,
        description: '',
      });
  
      // 表单验证规则
      const foodFormRules = reactive({
        name: [
          { required: true, message: '请输入食品名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择食品分类', trigger: 'change' }
        ],
        cityId: [
          { required: true, message: '请选择所属城市', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入食品描述', trigger: 'blur' }
        ]
      });
  
      // 根据过滤条件筛选食品
      const filteredFoodList = computed(() => {
        if (!foodList.value) return [];
  
        return foodList.value.filter(item => {
          const matchQuery = searchQuery.value
              ? (item.food.name && item.food.name.includes(searchQuery.value)) ||
                (item.food.category && item.food.category.includes(searchQuery.value)) ||
                (item.food.description && item.food.description.includes(searchQuery.value))
              : true;
  
          const matchCategory = categoryFilter.value !== ''
              ? item.food.category === categoryFilter.value
              : true;
  
          return matchQuery && matchCategory;
        });
      });
  
      // 获取食品分类对应的标签类型
      const getFoodCategoryType = (category) => {
        switch (category) {
          case '海鲜': return 'primary';
          case '主食': return 'success';
          case '小吃': return 'warning';
          case '肉类': return 'danger';
          case '火锅': return 'info';
          default: return 'default';
        }
      };
  
      // 获取食品列表
      // 获取食品列表
const fetchFoodList = () => {
  loading.value = true;
  selectAllFood()
    .then(({ state, message, data }) => {
      if (state === 0 && data) {
        foodList.value = data;
        totalFoods.value = data.length;
      } else {
        ElMessage.error(message || '获取食品列表失败');
      }
    })
    .catch((error) => {
      console.error('获取食品列表出错:', error);
      ElMessage.error('获取食品列表失败');
    })
    .finally(() => {
      loading.value = false;
    });
};
  
      // 搜索食品
      const handleSearch = () => {
        currentPage.value = 1;
        // 实际项目中可能需要调用接口进行搜索，这里只是前端过滤
      };
  
      // 变更每页显示数量
      const handleSizeChange = (val) => {
        pageSize.value = val;
        // 如果是服务端分页，这里需要重新请求数据
      };
  
      // 变更当前页码
      const handleCurrentChange = (val) => {
        currentPage.value = val;
        // 如果是服务端分页，这里需要重新请求数据
      };
  
      // 查看食品
      const handleViewFood = (row) => {
        selectedFood.value = row;
        Object.assign(foodForm, JSON.parse(JSON.stringify(row.food)));
        dialogType.value = 'view';
        dialogVisible.value = true;
      };
  
      // 编辑食品
      const handleEditFood = (row) => {
        selectedFood.value = row;
        Object.assign(foodForm, JSON.parse(JSON.stringify(row.food)));
        dialogType.value = 'edit';
        dialogVisible.value = true;
      };
  
      // 添加食品
      const handleAddFood = () => {
        Object.keys(foodForm).forEach(key => {
          foodForm[key] = key === 'cityId' ? 1 : '';
        });
        dialogType.value = 'add';
        dialogVisible.value = true;
      };
  
      // 删除食品
      const handleDeleteFood = (row) => {
        selectedFood.value = row;
        deleteDialogVisible.value = true;
      };
  
      // 确认删除
      // 确认删除
const confirmDelete = () => {
  loading.value = true;
  deleteFood(selectedFood.value.food.id)
    .then(({ state, message }) => {
      if (state === 0) {
        ElMessage.success('删除成功');
        deleteDialogVisible.value = false;
        // 从列表中移除
        const index = foodList.value.findIndex(item => item.food.id === selectedFood.value.food.id);
        if (index !== -1) {
          foodList.value.splice(index, 1);
        }
      } else {
        ElMessage.error(message || '删除失败');
      }
    })
    .catch((error) => {
      console.error('删除食品出错:', error);
      ElMessage.error('删除失败');
    })
    .finally(() => {
      loading.value = false;
    });
};
      // 城市与邮编的映射
      const cityZipCodeMapping = {
  石家庄: "130100",
  唐山: "130200",
  秦皇岛: "130300",
  邯郸: "130400",
  邢台: "130500",
  保定: "130600",
  张家口: "130700",
  承德: "130800",
  沧州: "130900",
  廊坊: "131000",
  衡水: "131100"
};
      // 提交食品表单
const submitFoodForm = () => {
  if (!foodFormRef.value) return;

  foodFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const apiFunc = dialogType.value === 'add' ? addNewFood : updateFood;
      
      apiFunc(foodForm)
        .then(({ state, message }) => {
          if (state === 0) {
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
            dialogVisible.value = false;

            if (dialogType.value === 'add') {
              // 模拟添加到列表
              const newFood = {
                food: { ...foodForm, id: Date.now() }, // 模拟生成ID
                cityName: '石家庄' // 假设城市名称
              };
              foodList.value.unshift(newFood);
            } else {
              // 更新列表中的数据
              const index = foodList.value.findIndex(item => item.food.id === foodForm.id);
              if (index !== -1) {
                foodList.value[index].food = { ...foodList.value[index].food, ...foodForm };
              }
            }
            
            // 刷新食品列表
            fetchFoodList();
          } else {
            ElMessage.error(message || (dialogType.value === 'add' ? '添加失败' : '更新失败'));
          }
        })
        .catch((error) => {
          console.error(dialogType.value === 'add' ? '添加食品出错:' : '更新食品出错:', error);
          ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};
  
      // 图片上传成功回调
      const handleImageSuccess = (response, file) => {
        // 假设上传接口返回的格式是 { state: 0, data: { url: '图片地址' } }
        if (response.state === 0 && response.data) {
          foodForm.image = response.data.url;
          ElMessage.success('图片上传成功');
        } else {
          ElMessage.error('图片上传失败');
        }
      };
  
      // 图片上传前的验证
      const beforeImageUpload = (file) => {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
  
        if (!isJPG && !isPNG) {
          ElMessage.error('图片只能是JPG或PNG格式!');
          return false;
        }
        if (!isLt2M) {
          ElMessage.error('图片大小不能超过2MB!');
          return false;
        }
        return true;
      };
  
      // 生命周期钩子
      onMounted(() => {
        fetchFoodList();
      });
  
      return {
        loading,
        foodList,
        searchQuery,
        categoryFilter,
        dialogVisible,
        dialogType,
        deleteDialogVisible,
        selectedFood,
        currentPage,
        pageSize,
        totalFoods,
        isAdmin,
        foodFormRef,
        foodForm,
        foodFormRules,
        filteredFoodList,
        getFoodCategoryType,
        handleSearch,
        handleSizeChange,
        handleCurrentChange,
        handleViewFood,
        handleEditFood,
        handleAddFood,
        handleDeleteFood,
        confirmDelete,
        submitFoodForm,
        handleImageSuccess,
        beforeImageUpload
      };
    }
  };
  </script>
  
  <style scoped>
  .food-manage-container {
    padding: 20px;
  }
  
  .operation-area {
    margin-bottom: 20px;
  }
  
  .search-wrapper {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  .search-input {
    width: 220px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .description-cell {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 300px;
  }
  
  .food-image {
    width: 50px;
    height: 50px;
    border-radius: 4px;
  }
  
  .no-image {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50px;
    height: 50px;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #909399;
  }
  
  .food-uploader {
    width: 150px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
  }
  
  .food-uploader:hover {
    border-color: #409EFF;
  }
  
  .food-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  
  .food-cover {
    width: 150px;
    height: 150px;
    display: block;
    object-fit: cover;
  }
  
  .delete-confirm {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .warning-icon {
    font-size: 24px;
    color: #E6A23C;
  }
  
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 20px;
  }
  </style>